package org.kalai.unifypay.tfb.pay;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.tfb.util.RequestUtil;

/**
 * 天付宝支付结果查询
 * 
 * @author nicholas
 *
 */
public class TFBAgentPayQueryService {

	private static final Logger log = Logger.getLogger(TFBAgentPayQueryService.class);

	private static final String AGENT_SINGLE_PAY_QUERY_URI = "api_pay_single_query.cgi";

	private static final String TEST_UTL = "http://apitest.tfb8.com/cgi-bin/v2.0/"; // 测试服务地址

	/**
	 * 参数二选一，
	 * 
	 * @param sp_serialno
	 * @param tfb_serialno
	 * @return
	 */
	public static Map<String, String> agentPayQuery(String sp_serialno, String tfb_serialno) {

		Map<String, String> map = new HashMap<String, String>();
		if (StringUtils.isBlank(sp_serialno) && StringUtils.isBlank(tfb_serialno)) {
			log.info("sp_serialno and tfb_serialno is null");
			map.put("respCode", "01");
			map.put("respDesc", "sp_serialno and tfb_serialno is null");
			return map;
		}
		// String serviceUrl = Constant.TFB_SERVICE_URL + AGENT_SINGLE_PAY_URI;
		// //正式
		String serviceUrl = TEST_UTL + AGENT_SINGLE_PAY_QUERY_URI; // 测试
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = format.format(date);

		TreeMap<String, String> paramsMap = new TreeMap<String, String>();
		paramsMap.put("version", "1.0"); // 固定填1.0
		paramsMap.put("spid", Constant.TFB_AGENT_PAY_SPID_TEST); // 填写国采分配的商户号
		paramsMap.put("sp_reqtime", time); // 系统发送时间，14位固定长度
		paramsMap.put("sp_serialno", sp_serialno); // 商户交易单号，商户保证其在本系统唯一
		paramsMap.put("tfb_serialno", tfb_serialno); // 天付宝代付单号

		log.info("参数:" + paramsMap);
		map = RequestUtil.sendRequst(serviceUrl, paramsMap);
		log.info("结果:" + map);

		return map;
	}

	// 20161020051532 2016102000005400
	public static void main(String[] args) throws UnsupportedEncodingException {
		String sp_serialno = "20161020051532";
		String tfb_serialno = "2016102000005400";
		Map<String, String> map = agentPayQuery(sp_serialno, tfb_serialno);
		System.out.println(map);
	}
}
